// 开发文档：https://uniapp.dcloud.io/uniCloud/clientdb?id=action
const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate

module.exports = {
	before: async (state, event) => {
		state.transaction = await db.startTransaction()
	},
	after: async (state, event, error, result) => {
		uniCloud.logger.log('action after', state)
		try{
			if (error) {
				throw error
			}
			if (state.type !== 'read') {
				let collection = db.collection("t3ds-mall-sku")
				var res = await collection.aggregate()
					.match({
						goods_id: state.newData.goods_id
					})
					.group({
						_id: null,
						totalStock: $.sum("$stock"),
						sellCount: $.sum("$sellCount"),
						unrealSellCount: $.sum("$unrealSellCount")
					})
					.end()
				let data = {
					totalStock: res.data[0].totalStock,
					totalSellCount: res.data[0].sellCount + res.data[0].unrealSellCount
				}
				res = await collection.where({
						goods_id: state.newData.goods_id
					})
					.orderBy("price", "asc")
					.limit(1)
					.get()
				data.price = res.data[0].price
				data.market_price = res.data[0].market_price
				await state.transaction.collection("t3ds-mall-goods").doc(state.newData.goods_id).update(data)
			}
			await state.transaction.commit()
		}catch(e){
			console.error(e)
			await state.transaction.rollback()
			throw e
		}
		return result
	}
}
